package com.example.qaplatform.controller;

import com.example.qaplatform.entity.ChatEntity;
import com.example.qaplatform.entity.History1Entity;
import com.example.qaplatform.repository.ChatRepository;
import com.example.qaplatform.repository.History1Repository;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@RestController
@RequestMapping("/api/chat")
public class ChatController {
    @Autowired
    private ChatRepository chatRepository;
    @Autowired
    private History1Repository history1Repository;

    @Value("${ragflow.api.key}")
    private String ragflowApiKey;

    // 1. 创建会话
    @PostMapping("/create")
    public ChatEntity createChat(@RequestBody Map<String, Object> req) {
        Long userId = Long.valueOf(req.get("userId").toString());
        String title = req.get("title").toString();
        ChatEntity chat = new ChatEntity();
        chat.setUserId(userId);
        chat.setTitle(title);
        chat.setCreateTime(LocalDateTime.now());
        return chatRepository.save(chat);
    }

    // 2. 查询用户所有会话
    @GetMapping("/list/{userId}")
    public List<ChatEntity> listChats(@PathVariable Long userId) {
        return chatRepository.findByUserIdOrderByCreateTimeDesc(userId);
    }

    // 3. 查询某会话下所有消息
    @GetMapping("/history/{chatId}")
    public List<History1Entity> listHistory(@PathVariable Long chatId) {
        return history1Repository.findByChatIdOrderByCreateTimeAsc(chatId);
    }

    // 4. 发送消息（保存到history1）
    @PostMapping(value = "/send", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public History1Entity sendMessage(
            @RequestPart("data") String data,
            @RequestPart(value = "image", required = false) MultipartFile image) {
        // 反序列化data
        Map<String, Object> req;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            req = objectMapper.readValue(data, Map.class);
        } catch (Exception e) {
            throw new RuntimeException("参数解析失败");
        }
        Long chatId = Long.valueOf(req.get("chatId").toString());
        Long userId = Long.valueOf(req.get("userId").toString());
        String question = req.get("question").toString();

        String docId = null;
        String datasetId = "156c7da8589011f0bd3f0242ac120006";
        if (image != null && !image.isEmpty()) {
            try {
                // 1. 上传图片到ragflow知识库，获取doc_id
                String uploadUrl = "http://localhost/api/v1/datasets/" + datasetId + "/documents";
                HttpHeaders uploadHeaders = new HttpHeaders();
                uploadHeaders.set("Authorization", "Bearer " + ragflowApiKey);
                uploadHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
                MultiValueMap<String, Object> uploadBody = new LinkedMultiValueMap<>();
                uploadBody.add("file", new ByteArrayResource(image.getBytes()) {
                    @Override
                    public String getFilename() {
                        return image.getOriginalFilename();
                    }
                });
                HttpEntity<MultiValueMap<String, Object>> uploadEntity = new HttpEntity<>(uploadBody, uploadHeaders);
                RestTemplate restTemplate = new RestTemplate();
                ResponseEntity<Map> uploadResp = restTemplate.postForEntity(uploadUrl, uploadEntity, Map.class);
                // 解析doc_id
                if (uploadResp.getStatusCode() == HttpStatus.OK && uploadResp.getBody() != null) {
                    Object dataObj = uploadResp.getBody().get("data");
                    if (dataObj instanceof Map) {
                        Object idObj = ((Map) dataObj).get("id");
                        if (idObj != null) docId = idObj.toString();
                    } else if (dataObj instanceof List && !((List) dataObj).isEmpty()) {
                        Object first = ((List) dataObj).get(0);
                        if (first instanceof Map) {
                            Object idObj = ((Map) first).get("id");
                            if (idObj != null) docId = idObj.toString();
                        }
                    }
                }
                // 2. 上传成功后自动分配chunk
                if (docId != null) {
                    String chunkUrl = "http://localhost/api/v1/datasets/" + datasetId + "/documents/" + docId + "/chunks";
                    HttpHeaders chunkHeaders = new HttpHeaders();
                    chunkHeaders.set("Authorization", "Bearer " + ragflowApiKey);
                    chunkHeaders.setContentType(MediaType.APPLICATION_JSON);
                    Map<String, Object> chunkBody = new HashMap<>();
                    chunkBody.put("content", "图片分块"); // 可自定义
                    chunkBody.put("important_keywords", new ArrayList<>());
                    HttpEntity<Map<String, Object>> chunkEntity = new HttpEntity<>(chunkBody, chunkHeaders);
                    restTemplate.postForEntity(chunkUrl, chunkEntity, Map.class);
                }
            } catch (Exception e) {
                docId = null;
            }
        }

        // 3. 调用 ragflow API 获取 answer
        String answer = "";
        try {
            RestTemplate restTemplate = new RestTemplate();
            String chatIdForRagflow = "03c542b05bf611f0996d0242ac120006"; // 你的 dialogId
            String apiUrl = "http://localhost/api/v1/chats_openai/" + chatIdForRagflow + "/chat/completions";
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + ragflowApiKey);
            headers.setContentType(MediaType.APPLICATION_JSON);

            Map<String, Object> payload = new HashMap<>();
            payload.put("model", "qwen2.5vl:3b");
            List<Map<String, Object>> messages = new ArrayList<>();
            Map<String, Object> userMsg = new HashMap<>();
            userMsg.put("role", "user");
            userMsg.put("content", question);
            if (docId != null) {
                List<String> docIds = new ArrayList<>();
                docIds.add(docId);
                userMsg.put("doc_ids", docIds);
            }
            messages.add(userMsg);
            payload.put("messages", messages);
            payload.put("stream", false);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(payload, headers);
            ResponseEntity<Map> response = restTemplate.postForEntity(apiUrl, entity, Map.class);
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Object choices = response.getBody().get("choices");
                if (choices instanceof List && !((List) choices).isEmpty()) {
                    Object first = ((List) choices).get(0);
                    if (first instanceof Map) {
                        Map firstMap = (Map) first;
                        Object message = firstMap.get("message");
                        if (message instanceof Map) {
                            answer = (String) ((Map) message).get("content");
                        }
                    }
                }
            }
            System.out.println("ragflow response: " + response.getBody());
        } catch (Exception e) {
            answer = "后端异常: " + e.getMessage();
        }

        // 4. 保存到 history1
        History1Entity msg = new History1Entity();
        msg.setChatId(chatId);
        msg.setUserId(userId);
        msg.setQuestion(question);
        msg.setAnswer(answer);
        msg.setImageUrl(null); // 如需保存图片可存URL
        msg.setCreateTime(LocalDateTime.now());
        return history1Repository.save(msg);
    }
} 